package easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution_594 {

    /*public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int max = 0;
        int windowLeftIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            int sub;
            while ((sub = nums[i] - nums[windowLeftIndex]) > 1) {
                windowLeftIndex++;
            }
            if (sub == 1) {
                max = Math.max(max, i - windowLeftIndex + 1);
            }
        }
        return max;
    }*/
    public int findLHS(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            Integer count = map.getOrDefault(num, 0);
            map.put(num, count + 1);
        }
        int max = 0;
        for (int num : nums) {
            Integer a = map.get(num);
            if (map.containsKey(num - 1)) {
                Integer count = map.get(num - 1) + a;
                max = Math.max(count, max);
            }
            if (map.containsKey(num + 1)) {
                Integer count = map.get(num + 1) + a;
                max = Math.max(count, max);
            }
        }
        return max;
    }
    /*public int findLHS(int[] nums) {
        if (nums.length < 2) {
            return 0;
        }
        Arrays.sort(nums);
        int maxCount = 0, count = 0;
        boolean flag = false;
        for (int i = 1, lastIndex = 0; i < nums.length; ) {
            int sub = nums[i] - nums[i - count - 1];
            if (sub < 2) {
                if (sub == 0) {
                    lastIndex = i;
                } else {
                    flag = true;
                }
                count++;
                i++;
            } else {
                if (flag) {
                    maxCount = Math.max(maxCount, count + 1);
                    flag = false;
                }
                count = 0;
                lastIndex++;
                i = lastIndex + 1;
            }
        }
        if (flag) {
            maxCount = Math.max(maxCount, count + 1);
        }
        return maxCount;
    }*/

    public static void main(String[] args) {
        Solution_594 model = new Solution_594();
        System.out.println(model.findLHS(new int[]{1, 3, 2, 2, 5, 2, 3, 7}));
        System.out.println(model.findLHS(new int[]{1, 3, 2, 2, 3, 2, 3, 3}));
        System.out.println(model.findLHS(new int[]{1, 1, 1, 1}));
        System.out.println(model.findLHS(new int[]{1,3,5,7,9,11,13,15,17}));
        System.out.println(model.findLHS(new int[]{1,4,1,3,1,-14,1,-13}));
        System.out.println(model.findLHS(new int[]{1, 2, 3, 4, 6, 5, -5, 10, -1, -2, 5, 4, 4, -1, 7}));
    }
}
